package com.tencent.qf.common.gateway.qwRobot;

import com.tencent.qf.common.util.RateLimiterUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;

/**
 * @author: p_haojiawu@tencent.com
 * @date: 2023-06-06 18:02
 **/

@Service
@Slf4j
public class QwRobotClient {

    @Resource
    private QwRobotProperties qwRobotProperties;

    @Resource
    private RateLimiterUtil rateLimiterUtil;

    public String post(String data) throws IOException {
        rateLimiterUtil.qwRobotAcquire(1);
        CloseableHttpClient httpclient;
        // 本地调试代理
        if (qwRobotProperties.getIsProxy()) {
            URL proxyUrlObject = new URL(qwRobotProperties.getProxyUrl());
            HttpHost proxy = new HttpHost(proxyUrlObject.getHost(), proxyUrlObject.getPort(), proxyUrlObject.getProtocol());
            RequestConfig defaultRequestConfig = RequestConfig.custom()
                    .setProxy(proxy)
                    .build();
            httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        } else {
            httpclient = HttpClients.createDefault();
        }
        String url = qwRobotProperties.getUrl() + qwRobotProperties.getToken();
        // 是否开启debug
        if (qwRobotProperties.getIsDebug()) {
            url = url + "&debug=1";
        }
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(data, "utf-8"));

        CloseableHttpResponse response = httpclient.execute(httpPost);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        log.info("请求数据======>{}", data);
        log.info("发送微信的响应数据======>{}", resp);
        return resp;
    }
}
